<?php
/**
 *
 * User: thikpanax
 * Date: 2019/12/24
 * Time: 0:14
 */

namespace App\TraitClass;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

trait PassportProxyTrait
{
    /**
     * 获取token
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function authenticate($guard = 'wap', $username, $password)
    {
        $client = new Client();

        try {
            $url = request()->root() . '/wap/oauth/token';

            $params = array_merge(config('passport.proxy'), [
                'username' => $username,
                'password' => $password,
                'provider' => $guard
            ]);

            $respond = $client->post($url, ['form_params' => $params]);

        } catch (RequestException $exception) {

            return false;
            abort(401, $exception->getMessage());
        }

        if ($respond->getStatusCode() !== 401) {
            return json_decode($respond->getBody()->getContents(), true);
        }

        return false;
        //abort(401, '账号或密码错误');
    }

    /**
     * 刷新token
     *
     * @return void
     */
    public function getRefreshToken($refresh_token = '')
    {

        $client = new Client();

        try {
            $url = request()->root() . '/wap/oauth/token';

            $params = array_merge(config('passport.refresh_token'), [
                'refresh_token' => $refresh_token,
            ]);

            $respond = $client->request('POST', $url, ['form_params' => $params]);
        } catch (RequestException $exception) {
            //abort(401, '请求失败，服务器错误');
            return false;
        }

        if ($respond->getStatusCode() !== 401) {
            return json_decode($respond->getBody(), true);
        }
        //abort(401, '不正确的 refresh_token');
        return false;
    }

}